package syscommand

import (
	"errors"
	"strings"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
)

type MakeCtl struct {
	CtlName string
	BaseCmd
}

func NewMakeCtl() *MakeCtl {
	return &MakeCtl{}
}

func (mc *MakeCtl) Configure() {
	// fmt.Println("MakeCtl -> Configure")
	mc.StringVar(&mc.CtlName, "ctlName", "", "控制器名称，可以指定包名")
}

func (mc *MakeCtl) Execute() error {
	// fmt.Printf("%+v\n", mc)
	if len(mc.CtlName) == 0 {
		return errors.New("控制器名称不能为空")
	}

	path, pkg, controller, parseErr := mc.ParsePathAndPkg(mc.CtlName, "controller")
	if parseErr != nil {
		return parseErr
	}

	filename := path + helper.CamelString(controller, false) + ".go"

	var ctlTplStr string
	tplFile := enum.ROOT_DIR + "console/tpl/controller.tpl"
	// fmt.Println("tplFile ========== ", tplFile)

	if err, val := helper.ReadFileContent(tplFile, false); err != nil {
		return err
	} else {
		ctlTplStr = val
	}
	// fmt.Println("======= before ======== ", ctlTplStr)

	ctlTplStr = strings.ReplaceAll(ctlTplStr, "{{pkg}}", pkg)
	ctlTplStr = strings.ReplaceAll(ctlTplStr, "{{ctlName}}", controller)
	// fmt.Println("========= after ========== ", ctlTplStr)

	if err := helper.WriteToFile(filename, ctlTplStr); err != nil {
		return err
	}

	return nil
}
